package com.zhangfb95.crosschain.console.command;

import com.zhangfb95.crosschain.console.enums.CommandEnum;
import com.zhangfb95.crosschain.infra.model.Result;
import com.zhangfb95.crosschain.infra.util.json.JsonUtil;
import com.zhangfb95.crosschain.sdk.CrossChainClient;
import com.zhangfb95.crosschain.sdk.infra.model.api.request.server.rpcchainaccount.RpcChainAccountAddApiReq;
import com.zhangfb95.crosschain.sdk.infra.model.api.request.server.rpcchainaccount.RpcChainAccountListApiReq;
import com.zhangfb95.crosschain.sdk.infra.model.api.response.server.rpcchainaccount.RpcChainAccountListApiRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangfubing
 * @since 2023/12/21
 */
@Component
public class ListChainAccountCommand implements Command {

    @Autowired
    private CrossChainClient crossChainClient;
    @Autowired
    private JsonUtil jsonUtil;

    @Override
    public CommandEnum command() {
        return CommandEnum.LIST_CHAIN_ACCOUNT;
    }

    @Override
    public boolean handle(String[] args) {
        if (isHelp(args)) {
            printHelpInfo();
            return false;
        }
        String chainPath;
        if (args.length > 0) {
            chainPath = args[0];
        } else {
            chainPath = null;
        }

        RpcChainAccountListApiReq apiReq = new RpcChainAccountListApiReq().setChainPath(chainPath);
        Result<RpcChainAccountListApiRes> apiRes = crossChainClient.listChainAccount(apiReq);
        if (apiRes.isSuccess()) {
            System.out.println("chainAccounts: \n" + jsonUtil.toPrettyJsonQuietly(apiRes.getData().getList()));
        } else {
            System.out.println("Result: " + apiRes.getMsg());
        }
        return false;
    }

    private void printHelpInfo() {
        System.out.println("Usage: addChainAccount [keyStoreType] [data]]");
        System.out.println("keyStoreType: base64, file");
        RpcChainAccountAddApiReq sampleApiReq = new RpcChainAccountAddApiReq();
        Map<String, String> properties = new HashMap<>();
        properties.put("key1", "value1");
        sampleApiReq.setProperties(properties);
        System.out.println("data: " + jsonUtil.toJsonQuietly(sampleApiReq));
    }
}
